from weatherFetcher import WeatherFetcher
from weatherDisplay import Display

""" Debug Mode """
DEBUG = 1

""" Class Constants """ 
NOW = 0
DAY_1 = 1
DAY_2 = 2
DAY_3 = 3
TIMES = {0:'low' , 1:'high'}


class WeatherModule():
    """
    This class represents the module.
    The weather module is responsible for the Applications logics and calculations.
    """
        
    def __init__(self):
        '''
        Constructor
        '''
        self.wf = WeatherFetcher()
        self.display = Display()
        
        self.wf.fetch_weather("countries.txt")
        self.wf.dump_pools_to_file()
        
        """ For running the application locally without Internet access on local DB """ 
        #self.wf.load_pools_from_dump_file()
     
        if DEBUG:
            print "Done creating weather data base."    
        
    def return_by_range_day_time(self,low,high,day,time):
        """
        Return an array of City,Country which meet all the condition
        @param low: low value of temp
        @param high: high value of temp
        @param day: how many days away (1,2,3)
        @param time: day(0) or night (1)    
        """
        d_or_night = TIMES[time]
        
        results=[]
        for key,value in self.wf.weather_reports.items():
            try:
                temp_in_day = (value[day][d_or_night])
            except:
                continue
            if ((temp_in_day > low) and (temp_in_day < high)) : 
                results.append(key)
        self.display.wish_weather(day, time, low, high, results)
        

    def return_current_weather_city(self,city):
        """
        Returns the given city's current weather
        @param city: City's name 
        """
        ret = ["City Not Found"]
        for key,value in self.wf.weather_reports.items():
            try:
                if city in key : 
                    ret = []
                    ret.append("City name: " + city)
                    ret.append("Current temp : " + str(value[NOW]["temp_c"]))
                    ret.append("Current Condition: " + str(value[NOW]["condition"]))
                    ret.append("" + str(value[NOW]["humidity"]))
            except:
                pass
        self.display.todays_stats(ret)
    
    
    def return_no_rain(self):
        """
        Returns a list of cities that will not have rain in the next 3 days
        """
        
        results=[]
        for key,value in self.wf.weather_reports.items():
            rain = False
            for i in range(DAY_3):
                try:
                    if ("rain" in value[i + 1]['condition']):
                        rain = True
                        break
                except:
                    continue
            if (rain == False):
                results.append(key)
        
        self.display.no_rain(results)


    def return_forecast(self,city):
        """
        Returns a 3 day forecast for the given city.
        @param city: The city's name to which we want the forecast.
        """
        ret = "City Not Found"
        for key,value in self.wf.weather_reports.items():
            try:
                if city in key:
                    ret = []
                    for i in range(3): 
                        ret.append("In Day : " + str(value[i+1]['day_of_week']))
                        ret.append("High: " + str(value[i+1]['high']))
                        ret.append("Low: " + str(value[i+1]['low']))
                        ret.append("Condition: " + str(value[i+1]['condition'])+ "\n")
                    break
            except:
                ret = ["City Not Found"]
                continue     
        self.display.weather_forecast(city, ret)
    
    
    def return_stats(self):
        """
        Returns the statistics of: Max , Min and Average of the current data base.    
        """

        max = -1
        min = 100
        sum = 0
        count = 0
        
        for value in self.wf.weather_reports.itervalues():
            current_temp = value[NOW]['temp_c']
            sum += current_temp
            count += 1
            
            if (current_temp > max):
                max = current_temp
            
            if (current_temp < min):
                min = current_temp
        
        self.display.todays_stats([("MAX : " + str(max)), ("MIN: " + str(min)),("AVERAGE: " + str(sum/count))])

      
    def get_all_countries(self,countries_name ="countries.txt"):
        """
        Returns a list of all the countries the application handles.
        @param countries_name: A file that holds all the countries this application handles. 
        """
        c_file = open(countries_name, 'r');
        countries = []
        for country_title in c_file : 
            # Get the cities of each country
            data = country_title.split(",");
            countries.append(data[1][:-1]);
        return countries        


    def get_all_cities(self, country , countries_name ="countries.txt"):
        """
        Returns a list of all the cities that the given country has in the data base.
        @param countries_name: A file that holds all the countries this application handles.
        """
        country_code = ""
        c_file = open(countries_name, 'r');
        for country_title in c_file : 
            # Get the cities of each country
            data = country_title.split(",");
            if (data[1][:-1] == country):
                country_code = data[0]
                break
        
        cities  = []
        for item in self.wf.weather_reports.keys() : 
            if item.endswith(country_code):
                cities.append(item.split(",")[0])              
        return cities    